﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Diagnostics;
using System.IO;
using ProgNetComponents.Classes;
using ProgNetComponentsDx.Options;
using BuildHelper.Work.Tools;
using BuildHelper.BHTasks;

namespace BuildHelper.Work.JAVA
{
    public partial class BudowanieJavy : XtraForm
    {
        private JavaBuildTask JavaBuildTask = new JavaBuildTask();

        private void ReadBranch(string brancz)
        {
            DataSet ds = javaDataSet.Copy();
            javaDataSet.Clear();
            BudowanieJavyTools.ReadBranch(brancz, javaDataSet);
            BudowanieJavyTools.ApplyTemplate(javaDataSet, ds);
            DataRow r = javaDataSet.BUILD.SelectFirstRow("STM = 'GCM'");
            if (r != null)
                r["Pakuj"] = true;
        }

        public string Brancz
        {
            get { return lueBrancz.EditValue.AsString(); }
        }
        public event EventHandler BranczChanged;
        public bool Pojedyncza
        {
            get;
            private set;
        }
        public BudowanieJavy()
        {
            InitializeComponent();

            if (!this.IsDesignMode())
            {
                JavaBuildTask.TaskFinished += new EventHandler(JavaBuildTask_TaskFinished);
                modeProvider1.CurrentMode = ProgNetComponentsDx.Enums.FormMode.Edit;
               
                Setup.Brancze.BranczeTools.ActiveBranchChanged += new EventHandler(Tools_ActiveBranchChanged);
                lueBrancz.EditValue = Setup.Brancze.BranczeTools.ActiveBranch;
                
                javaGridControl1.LayoutName = "BudowanieJavy";

                shortcutProvider1.BeginInit();
                SetShortcut(errorsPanel1.BtnErrors, "BudowanieJavy.BtnErrors");
                SetShortcut(errorsPanel1.BtnFirstError, "BudowanieJavy.BtnFirstError");
                SetShortcut(errorsPanel1.BtnLogFirst, "BudowanieJavy.BtnLogFirst");
                SetShortcut(errorsPanel1.BtnBalmeFirst, "BudowanieJavy.BtnBalmeFirst");
                shortcutProvider1.EndInit();
            }
        }

        void JavaBuildTask_TaskFinished(object sender, EventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<object, EventArgs>(JavaBuildTask_TaskFinished), sender, e);
                return;
            }
            this.errorsPanel1.AddError(JavaBuildTask.Errors);
            this.dxErrorProvider1.SetError(meLog, JavaBuildTask.Errors.AsString(Constants.NewLineLinux));
        }
        private void SetShortcut(Control ctrl, string id)
        {
            var s = shortcutProvider1.GetSettings(ctrl);
            s.IsCustomShortcut = true;
            s.CustomShortcutId = id;
            s.DisplayTooltip = true;
            s.AllowEdit = true;
        }
        public BudowanieJavy(string brancz):this()
        {
            optionProvider1.GetSettings(lueServer).OptionId = null;
            optionProvider1.GetSettings(ceClean).OptionId = null;
            optionProvider1.GetSettings(ceDeploy).OptionId = null;
            optionProvider1.GetSettings(ceZatrzymajNaBledzie).OptionId = null;
            
            optionProvider1.RefreshAll();

            lueBrancz.EditValue = brancz;
            Pojedyncza = true;
            
            modeProvider1.GetSettings(lueBrancz).ReadOnlyModes = ProgNetComponentsDx.Enums.FormMode.All;
            modeProvider1.GetSettings(memoEdit1).ReadOnlyModes = ProgNetComponentsDx.Enums.FormMode.All;
            modeProvider1.GetSettings(memoEdit2).ReadOnlyModes = ProgNetComponentsDx.Enums.FormMode.All;

            modeProvider1.RefreshObject(lueBrancz);
            modeProvider1.RefreshObject(memoEdit1);
            modeProvider1.RefreshObject(memoEdit2);

            this.Text += " [" + brancz + "]";
        }
        protected override void OnClosed(EventArgs e)
        {
            base.OnClosed(e);
            JavaBuildTask.Cancel();
        }
        protected override void OnLoad(EventArgs e)
        {
            javaGridControl1.OpcjaZmieniajRazem = !Pojedyncza;
            base.OnLoad(e);
            Short.ShortForm.AddJavaForm(this);
            this.marqueeProgressBarControl1.Text = "";

        }
        void Tools_ActiveBranchChanged(object sender, EventArgs e)
        {
            if (!Pojedyncza)
                lueBrancz.EditValue = Setup.Brancze.BranczeTools.ActiveBranch;
        }

        private void btnBuduj_Click(object sender, EventArgs e)
        {
            Buduj();
        }

        private void btnDeployEar_Click(object sender, EventArgs e)
        {
            DeployEar();
        }

        private void btnAnuluj_Click(object sender, EventArgs e)
        {
            Anuluj();
        }

        private void btnPokazPelnyLog_Click(object sender, EventArgs e)
        {
            PokazPelnyLog();
        }
        
        #region budowanie

        private bool ValidateAll()
        {
            dxErrorProvider1.ClearErrors();
            string msg = "";
            return modeProvider1.ValidateRequiredEdits(ref msg);
        }

        #endregion

        private void btnRunSerwer_Click(object sender, EventArgs e)
        {
            RunServer();
        }

        private void lueBrancz_EditValueChanged(object sender, EventArgs e)
        {
            ReadBranch(lueBrancz.EditValue.AsString());
            int server = browserProvider1.GetColumnValueForEditValue(lueBrancz, "STP_BR_SERWER").AsInt(-1);
            if (server > -1)
                lueServer.EditValue = server;
            else
                lueServer.EditValue = DBNull.Value;
            if (BranczChanged != null)
                BranczChanged(this, EventArgs.Empty);
        }

        private void templateControl1_ReadingTemplate(object sender, Template.MergingDataSetEventArgs e)
        {
            foreach (var r in javaDataSet.BUILD)
            {
                r["Buduj"] = false;
                if (r["STM"].AsString() != "GCM")
                    r["Pakuj"] = false;
            }
            foreach (DataRow x in e.TemplateDataSet.Tables["BUILD"].Select())
            {
                if (javaDataSet.BUILD.SelectFirstRow("STM = " + x["STM"].AsString().EscapeSql()) == null)
                {
                    x.Delete();
                }
            }
            this.javaDataSet.GCM_SETTINGS.Clear();
        }
        private void templateControl1_TemplateRead(object sender, EventArgs e)
        {
            foreach (var r in javaDataSet.BUILD)
            {
                if (r.IsGENERATEDNull())
                    r.GENERATED = false;
                if (r.IsPackWSNull())
                    r.PackWS = false;
            }
            
            if (javaDataSet.GCM_SETTINGS.Rows.Count == 0)
            {
                var r = javaDataSet.GCM_SETTINGS.NewRow();
                javaDataSet.GCM_SETTINGS.Rows.Add(r);
            }
            if (javaDataSet.GCM_SETTINGS.Rows.Count > 0)
            {
                foreach (DataColumn c in javaDataSet.GCM_SETTINGS.Columns)
                {
                    if (javaDataSet.GCM_SETTINGS.Rows[0][c].IsNull())
                        javaDataSet.GCM_SETTINGS.Rows[0][c] = false;
                }
            }
        }
       
        public void WczytajTemplate()
        {
            templateControl1.PerformReadTemplate();
        }

        public void Buduj()
        {
            if (!JavaBuildTask.IsRunning)
            {
                if (ValidateAll())
                {
                    InitTaskData(this.javaDataSet.Copy());
                    JavaBuildTask.IsDeploy = false;
                    JavaBuildTask.Run();
                }
            }
            else
            {
                this.ShowDxInfoDialog("Operacja w toku.");
            }
        }

        private void InitTaskData(DataSet ds)
        {
            this.errorsPanel1.ClearErrors();
            this.dxErrorProvider1.SetError(meLog, string.Empty);
            this.JavaBuildTask.Brancz = lueBrancz.EditValue.AsString();
            this.JavaBuildTask.AutoCreateFile = true;
            this.JavaBuildTask.Clean = ceClean.Checked;
            JavaBuildTask.Deploy = ceDeploy.Checked;
            JavaBuildTask.UpdateBuildXml = ceZmieniajBuildXml.Checked;
            this.JavaBuildTask.DataSet = ds as JavaDataSet;
            this.JavaBuildTask.Errors.Clear();
            this.JavaBuildTask.MemoAppender = this.memoBgAppender1;
            this.JavaBuildTask.ProgressBar = this.marqueeProgressBarControl1;
            this.JavaBuildTask.Server = this.lueServer.EditValue.AsInt();
            this.JavaBuildTask.ShowInfoAlert = true;
            this.JavaBuildTask.StopOnFirstError = ceZatrzymajNaBledzie.Checked;
        }
        public void DeployEar()
        {
            if (!JavaBuildTask.IsRunning)
            {
                if (ValidateAll())
                {
                    InitTaskData(this.javaDataSet.Copy());
                    JavaBuildTask.IsDeploy = true;
                    JavaBuildTask.Run();
                }
            }
            else
            {
                this.ShowDxInfoDialog("Operacja w toku.");
            }
        }

        public void RunServer()
        {
            if (lueServer.EditValue.IsNull())
            {
                this.ShowDxInfoDialog("Wybierz serwer.");
                return;
            }
            int serwerId = lueServer.EditValue.AsInt();
            GlobalTools.ServerTools.RunServer(serwerId, lueBrancz.EditValue.AsString(), OptionCache.GetOptionBoolValue(Init.InitFormOptionNames.Narzedzia.SerwerBringToFront), GlobalTools.ServerTools.ServerRestartType.Ask);
        }

        public void Anuluj()
        {
            JavaBuildTask.Cancel();
        }

        public void PokazPelnyLog()
        {
            JavaBuildTask.ShowLogFile();
        }

        private void btnGenInternalSDK_Click(object sender, EventArgs e)
        {
            if (lueBrancz.EditValue.IsNotNull())
                FormMain.Instance.GetInternalSdk(lueBrancz.EditValue.AsString());
            else this.ShowDxInfoDialog("Wybierz brancza");
        }

        private void btnGetLib3p_Click(object sender, EventArgs e)
        {
            if (lueBrancz.EditValue.IsNotNull())
            {
                DataRow r = browserProvider1.GetRowForEditValue(lueBrancz);
                if (r != null)
                {
                    string dir = r["STP_BR_KATALOG"].ToString();
                    dir = dir.TrimEnd('\\');
                    dir += @"\nd_src\gene\buildGeneLib3p.bat";
                    GlobalTools.FilesTools.RunFileUsingCmd(dir, lueBrancz.EditValue.AsString(), "buildGeneLib3p");
                }
            }
            else this.ShowDxInfoDialog("Wybierz brancza");
        }

        private void btnCleanBuildXml_Click(object sender, EventArgs e)
        {
            BudowanieJavyTools.ClearBuildXmls(lueBrancz.EditValue.AsString());
        }
        
    }

}
